package com.health.viewscontrols.medical.device.bg;

import android.bluetooth.BluetoothGatt;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.ToastUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.nova.health.ble.callback.OnDeviceConnectChangedListener;
import com.novabluetooth.data.DeviceShowSaveData;
import com.snbc.sdk.barcode.enumeration.HRIPosition;

import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

/**
 * 百捷三合一
 */
public class BGyuyueActivity extends BaseDeviceActivity {

    public final static UUID UUID_SERVICE = UUID.fromString("00001808-0000-1000-8000-00805f9b34fb");
    public final static UUID UUID_NOTIFY = UUID.fromString("00002a18-0000-1000-8000-00805f9b34fb");

    private BigDecimal jcresult = new BigDecimal(0l);
    private BleDevice fastBleDevice;

    @Override
    public void doBusiness() {
        tv_operation_tips.setText(com.nova.health.ble.R.string.bg_yuyue);

        BleManager.getInstance().init(getApplication());
        BleManager.getInstance()
                .enableLog(true)
                .setReConnectCount(1, 15000)
                .setConnectOverTime(20000)
                .setOperateTimeout(15000);

        startDevice();
    }

    @Override
    public void startDevice() {
        if (fastBleDevice == null) {
            showProgressDialog("正在连接" + deviceEnum.getTitle());
            BleManager.getInstance().scan(new BleScanCallback() {
                @Override
                public void onScanStarted(boolean success) {
                }

                @Override
                public void onLeScan(BleDevice bleDevice) {
                    super.onLeScan(bleDevice);
                }

                @Override
                public void onScanning(BleDevice bleDevice) {
                    Log.e(TAG, "onScanning: " + bleDevice.getName() + "  " + bleDevice.getMac() );
                    if (bleDevice != null && bleDevice.getMac() != null && deviceEnum.getMac().equals(bleDevice.getMac())) {
                        connectionPwBle();
                    }
                }

                @Override
                public void onScanFinished(List<BleDevice> scanResultList) {

                }
            });
        } else {
            ToastUtils.showShort("设备已连接，请等待测量结果");
            showProgressDialog("等待接收血糖数据");
        }
    }

    private void connectionPwBle() {
        BleManager.getInstance().connect(deviceEnum.getMac(), new BleGattCallback() {
            @Override
            public void onStartConnect() {
                blueToothState.setText("蓝牙开始连接");
                showProgressDialog("正在连接血糖设备");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.e(TAG, "onConnectFail: " +  exception.toString());
                blueToothState.setText("蓝牙连接失败");
                connectionPwBle();
            }

            @Override
            public void onConnectSuccess(final BleDevice bleDevice, BluetoothGatt gatt, int status) {
                //连接成功
                Log.e(TAG, "onConnectSuccess: " + bleDevice.getMac() );
                blueToothState.setText("蓝牙已连接");
                fastBleDevice = bleDevice;
                showProgressDialog("等待接收血糖数据");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getPwNotify(bleDevice);
                    }
                },1000);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                blueToothState.setText("蓝牙已断开连接");
                disconnectDevice();
                cancelProgressDialog();
            }
        });
    }

    private void getPwNotify(final BleDevice bleDevice) {
        BleManager.getInstance().notify(bleDevice,
                UUID_SERVICE.toString(),
                UUID_NOTIFY.toString(),
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        Log.e(TAG, "onNotifySuccess: " );
                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        Log.e(TAG, "onNotifyFailure: " +exception.toString());
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        //接收数据
//                        String hexString = HexUtil.formatHexString(data);
                        formatData(data);
                    }
                });
    }

    @Override
    public void update(String hexStr) {
        Log.e(TAG, "update: " + hexStr );
    }

    private void formatData(byte[] data) {
        //接收数据
        try {

            String hexString = HexUtil.formatHexString(data);
            Log.e(TAG, "formatData: " + hexString );
            if (TextUtils.isEmpty(hexString) && hexString.length() < 25) {
                return;
            }

            String type = hexString.substring(0, 2);
            String data1 = hexString.substring(20, 22);
            String data2 = hexString.substring(23, 24);
            int result = hexStringToInt(data2+ data1);
            tv_state.setText("获取测量结果成功");
            switch (type) {
                case "06":
                    //血糖
                    BigDecimal bg = new BigDecimal(result/10.0);
                    tv_result.setText("血糖测量结果：\n        " + bg.setScale(2, BigDecimal.ROUND_HALF_UP) +"mmol/L");
                    if (jcresult.compareTo(bg.setScale(2, BigDecimal.ROUND_HALF_UP)) == 0) {
                        return;
                    }
                    jcresult = bg.setScale(2, BigDecimal.ROUND_HALF_UP);
                    Log.e("xiaoxin","测量结果: "+"--" + jcresult);
                    tv_result.setText("血糖值： " + jcresult  + "mmol/L");
                    DeviceShowSaveData.getDataShow(jcresult +"", "BeneCheck");
                    DeviceShowSaveData.saveXuetangBj(jcresult +"");
                    break;
//                case "51":
//                    //尿酸设备
//                    BigDecimal ns = new BigDecimal((result * 0.1)/16.81 * 1000);
//                    tv_result.setText("尿酸测量结果：\n        " + ns.setScale(2, BigDecimal.ROUND_HALF_UP) +"μmol/L");
//                    if (jcresult.compareTo(ns.setScale(2, BigDecimal.ROUND_HALF_UP)) == 0) {
//                        return;
//                    }
//                    jcresult = ns.setScale(2, BigDecimal.ROUND_HALF_UP);
//                    tv_result.setText("尿酸值： " + jcresult  + "μmol/L");
//                    Log.e("xiaoxin","尿酸设备测量结果: "+"--" + jcresult);
//                    DeviceShowSaveData.getDataShow(jcresult +"", "BeneCheck-ns");
//                    DeviceShowSaveData.saveNs(jcresult +"");
//                    break;
//                case "61":
//                    //胆固醇设备
//                    BigDecimal dgc = new BigDecimal(result/38.66);
//                    tv_result.setText("胆固醇测量结果：\n        " + dgc.setScale(2, BigDecimal.ROUND_HALF_UP) +"mmol/L");
//                    if (jcresult.compareTo(dgc.setScale(2, BigDecimal.ROUND_HALF_UP)) == 0) {
//                        return;
//                    }
//                    jcresult = dgc.setScale(2, BigDecimal.ROUND_HALF_UP);
//                    tv_result.setText("胆固醇值： " + jcresult  + "mmol/L");
//                    Log.e("xiaoxin","胆固醇设备测量结果: "+"--" + jcresult);
//                    DeviceShowSaveData.getDataShow(jcresult +"", "BeneCheck-dgc");
//                    DeviceShowSaveData.saveDgc(jcresult +"");
//                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int hexStringToInt(String HexString) {
        int inJTFingerLockAddress = Integer.valueOf(HexString, 16);
        return inJTFingerLockAddress;
    }

    @Override
    public void disconnectDevice() {
        try {
            cancelProgressDialog();
            if (fastBleDevice != null) {
                BleManager.getInstance().stopNotify(fastBleDevice, UUID_SERVICE.toString(), UUID_NOTIFY.toString());
                //断开设备
                BleManager.getInstance().disconnectAllDevice();
                BleManager.getInstance().destroy();
                fastBleDevice = null;
            }
            BleManager.getInstance().cancelScan();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
